package com.csii.modules.project.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.api.Result;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.util.ConvertUtils;
import com.csii.core.util.oConvertUtils;
import com.csii.modules.project.mapper.entity.ProjectUser;
import com.csii.modules.project.controller.vo.ProjectUserVO;
import com.csii.modules.project.service.dto.ProjectUserDTO;
import com.csii.modules.project.mapper.entity.Project;
import com.csii.modules.project.service.dto.ProjectDTO;
import com.csii.modules.project.controller.vo.ProjectVO;
import com.csii.modules.project.controller.vo.ProjectVOPage;
import com.csii.modules.project.service.IProjectService;
import com.csii.modules.project.service.IProjectUserService;
import com.csii.autopoi.poi.excel.ExcelImportUtil;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.poi.excel.entity.ImportParams;
import com.csii.autopoi.web.def.NormalExcelConstants;
import com.csii.autopoi.web.view.EntityExcelView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.csii.core.annotation.AutoLog;

 /**
 * @Description: 项目
 * @Author: power-stdio
 * @Date:   2020-11-05
 * @Version: V1.0
 */
@Api(tags="项目")
@RestController
@RequestMapping("/project")
@Slf4j
public class ProjectController {
	@Autowired
	private IProjectService projectService;
	@Autowired
	private IProjectUserService projectUserService;
	
	/**
	 * 分页列表查询
	 *
	 * @param projectVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "项目-分页列表查询")
	@ApiOperation(value="项目-分页列表查询", notes="项目-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ProjectVO projectVO,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Project project = ConvertUtils.convert(Project.class,projectVO);
		QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
		Page<Project> page = new Page<Project>(pageNo, pageSize);
		IPage<Project> pageList = projectService.page(page, queryWrapper);
		IPage<ProjectVO> pageListVo = ConvertUtils.convertIPage(ProjectVO.class, pageList);
		return Result.ok(pageListVo);
	}
	
	/**
	 *   添加
	 *
	 * @param projectVOPage
	 * @return
	 */
	@AutoLog(value = "项目-添加")
	@ApiOperation(value="项目-添加", notes="项目-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ProjectVOPage projectVOPage) {
		ProjectDTO projectDTO = ConvertUtils.convert(ProjectDTO.class,projectVOPage);
		projectService.saveMain(projectDTO, ConvertUtils.convertList(ProjectUserDTO.class, projectVOPage.getProjectUserList()));
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param projectVOPage
	 * @return
	 */
	@AutoLog(value = "项目-编辑")
	@ApiOperation(value="项目-编辑", notes="项目-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ProjectVOPage projectVOPage) {
		ProjectDTO projectDTO = ConvertUtils.convert(ProjectDTO.class,projectVOPage);
		Project projectEntity = projectService.getById(projectDTO.getId());
		if(projectEntity==null) {
			return Result.error("未找到对应数据");
		}
		projectService.updateMain(projectDTO, ConvertUtils.convertList(ProjectUserDTO.class, projectVOPage.getProjectUserList()));
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目-通过id删除")
	@ApiOperation(value="项目-通过id删除", notes="项目-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		projectService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目-批量删除")
	@ApiOperation(value="项目-批量删除", notes="项目-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.projectService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目-通过id查询")
	@ApiOperation(value="项目-通过id查询", notes="项目-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Project project = projectService.getById(id);
		if(project==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(project);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目成员表通过主表ID查询")
	@ApiOperation(value="项目成员表主表ID查询", notes="项目成员表-通主表ID查询")
	@GetMapping(value = "/queryProjectUserByMainId")
	public Result<?> queryProjectUserListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ProjectUser> projectUserList = projectUserService.selectByMainId(id);
		return Result.ok(projectUserList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param project
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Project project) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

      //Step.2 获取导出数据
      List<Project> queryList = projectService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<Project> projectList = new ArrayList<Project>();
      if(oConvertUtils.isEmpty(selections)) {
          projectList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          projectList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ProjectVOPage> pageList = new ArrayList<ProjectVOPage>();
      for (Project main : projectList) {
          ProjectVOPage vo = ConvertUtils.convert(ProjectVOPage.class,main);
          List<ProjectUser> projectUserList = projectUserService.selectByMainId(main.getId());
          vo.setProjectUserList(ConvertUtils.convertList(ProjectUserVO.class, projectUserList));
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目列表");
      mv.addObject(NormalExcelConstants.CLASS, ProjectVOPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目数据", "导出人:"+sysUser.getRealname(), "项目"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
		  InputStream isr = null;
		  try {
			  isr = file.getInputStream();
              List<ProjectVOPage> list = ExcelImportUtil.importExcel(isr, ProjectVOPage.class, params);
              for (ProjectVOPage page : list) {
                  ProjectDTO po = ConvertUtils.convert(ProjectDTO.class,page);
                  projectService.saveMain(po, ConvertUtils.convertList(ProjectUserDTO.class, page.getProjectUserList()));
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
			  if (isr != null) {
				  try {
					  isr.close();
				  } catch (IOException e) {
					  e.printStackTrace();
				  }
			  }
		  }
      }
      return Result.ok("文件导入失败！");
    }

	 /**
	  * 分页列表查询
	  *
	  * @param userName
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "项目-列表查询")
	 @ApiOperation(value="项目-列表查询", notes="项目-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<?> queryList(@RequestParam(required = false) String userName,
								HttpServletRequest req) {
		 List<ProjectVO> pageListVo = null;
		 if (StringUtils.isEmpty(userName)) {
			 QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(new Project(), req.getParameterMap());
			 List<Project> pageList = projectService.list(queryWrapper);
			 pageListVo = ConvertUtils.convertList(ProjectVO.class, pageList);

		 }else{
			 List<ProjectDTO> pageList = projectService.queryList(userName);
			 pageListVo = ConvertUtils.convertList(ProjectVO.class, pageList);

		 }
		 return Result.ok(pageListVo);
	 }
}
